package com.coocaa.ops.admin.v1.mergeposter.provider.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coocaa.ops.plus.core.third.magic.MagicFeignClientService;
import com.coocaa.ops.plus.core.third.magic.handler.AiPosterMergeHandler;
import com.coocaa.ops.plus.core.third.magic.model.OriginMergeInfo;
import com.coocaa.ops.plus.core.third.magic.model.PosterMergeParamsInfo;
import com.coocaa.ops.admin.v1.mergeposter.handler.PosterMergeDataHandler;
import com.coocaa.ops.admin.v1.mergeposter.mapper.IAiPosterMergeMapper;
import com.coocaa.ops.admin.v1.mergeposter.model.internal.AiPosterMergeDbInfo;
import com.coocaa.ops.admin.v1.mergeposter.model.query.PosterMergeDbQueryModel;
import com.coocaa.ops.admin.v1.mergeposter.provider.IRefreshPosterMergeProvider;
import com.coocaa.ops.admin.v1.panel.biz.impl.BlockContentInfoBizImpl;
import com.coocaa.ops.admin.v1.panel.biz.impl.PanelInfoBizImpl;
import com.coocaa.ops.admin.v1.panel.biz.impl.PanelSubPanelRlsBizImpl;
import com.coocaa.ops.admin.v1.panel.model.query.SubPanelQueryModel;
import com.coocaa.ops.common.core.base.enums.ResourceTypeEnum;
import com.coocaa.ops.common.core.biz.panel.constant.PanelTypeConstants;
import com.coocaa.ops.common.core.biz.panel.constant.SubPanelVersionConstants;
import com.coocaa.ops.common.core.biz.panel.entity.BlockContentInfoEntity;
import com.coocaa.ops.common.core.biz.panel.entity.PanelInfoEntity;
import com.coocaa.ops.common.core.biz.panel.entity.SubPanelConfigInfo;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.exception.ExceptionUtil;
import com.coocaa.ops.common.tool.json.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author bjh
 * @description
 * @date 2021/1/8 14:29
 */
@Slf4j
@Service
public class RefreshPosterMergeProviderImpl implements IRefreshPosterMergeProvider {
    @Autowired
    private IAiPosterMergeMapper aiPosterMergeMapper;
    @Autowired
    private MagicFeignClientService magicFeignClientService;
    @Autowired
    private PanelSubPanelRlsBizImpl panelSubPanelRlsBiz;
    @Autowired
    private PanelInfoBizImpl panelInfoBiz;
    @Autowired
    private BlockContentInfoBizImpl blockContentInfoBiz;

    /**
     * 刷新板块合成海报-根据板块组id和版本
     *
     * @param id
     * @param version
     * @param checkHasMergePoster
     * @return
     */
    public boolean refreshPanelPosterMerge(Integer id, Integer version, boolean checkHasMergePoster) {
        PanelInfoEntity entity = panelInfoBiz.queryById(id);
        if (null == entity) {
            return false;
        }
        if (!PanelTypeConstants.isCanMergePoster(entity.getPanelType())) {
            return false;
        }
        if (null == version) {
            version = entity.getCurrentVersion();
        }
        List<AiPosterMergeDbInfo> aiPosterMergeInfoList = queryFinalAiPosterMergeInfoList(entity, version);
        log.info(entity.getId() + ": " + entity.getCurrentVersion() + ": " + JsonUtil.obj2Json(aiPosterMergeInfoList));
        if (CollectionUtils.isEmpty(aiPosterMergeInfoList)) {
            return false;
        }
        boolean isCurrentVersion = Objects.equals(version, entity.getCurrentVersion());
        String layoutJsonStr = getLayoutJson(id, isCurrentVersion, version);
        aiPosterMergeInfoList = PosterMergeDataHandler.handleMergePosterBlockPos(layoutJsonStr, aiPosterMergeInfoList);
        if (null == aiPosterMergeInfoList) {
            return false;
        }
        for (AiPosterMergeDbInfo aiPosterMergeDbInfo : aiPosterMergeInfoList) {
            this.handleEachAiPosterMergeInfo(aiPosterMergeDbInfo, checkHasMergePoster);
        }
        return isCurrentVersion;
    }


    /**
     * 重置板块合成海报-根据板块组id和版本
     *
     * @param id
     * @param version
     */
    @Override
    public boolean resetPanelPosterMerge(Integer id, Integer version) {
        PanelInfoEntity entity = panelInfoBiz.queryById(id);
        if (null == entity) {
            return false;
        }
        if (!PanelTypeConstants.isCanMergePoster(entity.getPanelType())) {
            return false;
        }
        if (null == version) {
            version = entity.getCurrentVersion();
        }
        List<AiPosterMergeDbInfo> aiPosterMergeInfoList = queryFinalAiPosterMergeInfoList(entity, version);
        if (CollectionUtils.isEmpty(aiPosterMergeInfoList)) {
            return false;
        }
        for (AiPosterMergeDbInfo aiPosterMergeDbInfo : aiPosterMergeInfoList) {
            resetBlockPosterMerge(aiPosterMergeDbInfo.getBlockId());
        }
        boolean isCurrentVersion = Objects.equals(version, entity.getCurrentVersion());
        return isCurrentVersion;
    }

    /**
     * 重置推荐位合成海报-根据推荐位id
     *
     * @param id
     */
    @Override
    public void resetBlockPosterMerge(Integer id) {
        BlockContentInfoEntity entityDb = blockContentInfoBiz.queryById(id);
        if (null != entityDb) {
            BlockContentInfoEntity update = new BlockContentInfoEntity();
            update.setMergePoster("");
            update.setId(entityDb.getId());
            blockContentInfoBiz.updateById(update);
        }
    }

    /**
     * 获取布局json
     *
     * @param id
     * @param isCurrentVersion
     * @param version
     * @return
     */
    private String getLayoutJson(Integer id, boolean isCurrentVersion, Integer version) {
        if (isCurrentVersion) {
            return aiPosterMergeMapper.getLayoutJsonForCurrentVersion(id);
        }
        return aiPosterMergeMapper.getLayoutJson(id, version);
    }


    private void handleEachAiPosterMergeInfo(AiPosterMergeDbInfo aiPosterMergeDbInfo, boolean checkHasMergePoster) {
        if (isHasMergePosterDb(aiPosterMergeDbInfo, checkHasMergePoster)) {
            return;
        }
        PosterMergeParamsInfo posterMergeParamsInfo = getPosterMergeParamsInfo(aiPosterMergeDbInfo);
        // 重置之前的合成海报-遴选任务(virgo项目已使用，此暂无)
        boolean resetBefore = isResetBefore(posterMergeParamsInfo);
        String mergePoster = getMergePoster(posterMergeParamsInfo, resetBefore);
        if (StringUtils.isBlank(mergePoster)) {
            return;
        }
        BlockContentInfoEntity entityDb = blockContentInfoBiz.queryById(aiPosterMergeDbInfo.getBlockId());
        if (null != entityDb) {
            BlockContentInfoEntity update = new BlockContentInfoEntity();
            update.setMergePoster(mergePoster);
            update.setId(entityDb.getId());
            blockContentInfoBiz.updateById(update);
        }
    }

    /**
     * 是否直接返回
     *
     * @param aiPosterMergeDbInfo
     * @param checkHasMergePoster
     * @return
     */
    private boolean isHasMergePosterDb(AiPosterMergeDbInfo aiPosterMergeDbInfo, boolean checkHasMergePoster) {
        return StringUtils.isBlank(aiPosterMergeDbInfo.getPictureUrl())
                || (checkHasMergePoster && StringUtils.isNotEmpty(aiPosterMergeDbInfo.getMergePosterDb()));
    }

    /**
     * 是否重置之前的遴选任务的合成海报
     *
     * @param posterMergeParamsInfo
     * @return
     */
    private boolean isResetBefore(PosterMergeParamsInfo posterMergeParamsInfo) {
        return null == posterMergeParamsInfo || CollectionUtils.isEmpty(posterMergeParamsInfo.getDrawList());
    }

    private PosterMergeParamsInfo getPosterMergeParamsInfo(AiPosterMergeDbInfo aiPosterMergeDbInfo) {
        OriginMergeInfo originMergeInfo = PosterMergeDataHandler.getOriginMergeInfo(aiPosterMergeDbInfo);
        PosterMergeParamsInfo posterMergeParamsInfo = AiPosterMergeHandler.getPosterMergeParamsInfo(originMergeInfo);
        return posterMergeParamsInfo;
    }

    private String getMergePoster(PosterMergeParamsInfo posterMergeParamsInfo, boolean resetBefore) {
        if (resetBefore) {
            return null;
        }
        try {
            String result = magicFeignClientService.aiPosterMerge(posterMergeParamsInfo);
            if (StringUtils.isBlank(result)) {
                return null;
            }
            JSONObject res = JSON.parseObject(result);
            String code = res.getString("code");
            if (Objects.equals("0", code)) {
                String url = res.getJSONObject("data").getString("url");
                return url;
            } else {
                log.error(result);
                return null;
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getErrorPrintLog("解析ai-poster合成海报信息", e));
            return null;
        }
    }

    /**
     * 查询海报合成所需的信息
     *
     * @param entity
     * @return
     */
    private List<AiPosterMergeDbInfo> queryFinalAiPosterMergeInfoList(PanelInfoEntity entity, Integer version) {
        if (PanelTypeConstants.isNormal(entity.getPanelType())) {
            return queryAiPosterMergeInfoListForNormalPanel(entity, version);
        } else if (PanelTypeConstants.isGroup(entity.getPanelType())) {
            return queryAiPosterMergeInfoListForGroupPanel(entity.getId(), version);
        }
        return null;
    }

    /**
     * 普通板块 - 查询海报合成所需的信息
     *
     * @param entity
     * @return
     */
    private List<AiPosterMergeDbInfo> queryAiPosterMergeInfoListForNormalPanel(PanelInfoEntity entity, Integer version) {
        PosterMergeDbQueryModel queryModel = new PosterMergeDbQueryModel(entity.getId(), version, ResourceTypeEnum.PANEL.getValue());
        return queryAiPosterMergeInfoList(queryModel, entity.getHasDmp());
    }

    /**
     * 查询海报合成所需的信息
     *
     * @param model
     * @param hasDmp
     * @return
     */
    private List<AiPosterMergeDbInfo> queryAiPosterMergeInfoList(PosterMergeDbQueryModel model, Integer hasDmp) {
        List<AiPosterMergeDbInfo> result = InstanceUtil.newArrayList();
        List<AiPosterMergeDbInfo> common = aiPosterMergeMapper.queryCommonBlockPosterMergeInfoList(model);
        if (CollectionUtils.isNotEmpty(common)) {
            result.addAll(common);
        }
        if (Objects.equals(1, hasDmp)) {
            List<AiPosterMergeDbInfo> dmp = aiPosterMergeMapper.queryDmpBlockPosterMergeInfoList(model);
            if (CollectionUtils.isNotEmpty(dmp)) {
                result.addAll(dmp);
            }
        }
        return result;
    }

    /**
     * 分组板块 - 查询海报合成所需的信息
     *
     * @return
     */
    private List<AiPosterMergeDbInfo> queryAiPosterMergeInfoListForGroupPanel(Integer id, Integer version) {
        List<AiPosterMergeDbInfo> result = InstanceUtil.newArrayList();
        SubPanelQueryModel model = new SubPanelQueryModel(id, version);
        List<SubPanelConfigInfo> subPanelConfigList = panelSubPanelRlsBiz.getMapper().queryRlsSubPanelList(model);
        for (SubPanelConfigInfo subPanelConfigInfo : subPanelConfigList) {
            PosterMergeDbQueryModel queryModel = new PosterMergeDbQueryModel(subPanelConfigInfo.getId(), SubPanelVersionConstants.SUB_PANEL_VERSION, ResourceTypeEnum.SUB_PANEL.getValue());
            List<AiPosterMergeDbInfo> dataForEachSubPanel = queryAiPosterMergeInfoList(queryModel, subPanelConfigInfo.getHasDmp());
            if (CollectionUtils.isNotEmpty(dataForEachSubPanel)) {
                result.addAll(dataForEachSubPanel);
            }
        }
        return result;
    }


}
